<?php

/**
 * 短信发送类
 *
 * @author suning <snsnsky@gmail.com>
 *
 * $Id$
 */

namespace Notice;

use Common\Bridge;
use Queue\Queue;

/**
 * 签名助手 2017/11/19
 *
 * Class SignatureHelper
 */
class SignatureHelper
{

    /**
     * 生成签名并发起请求
     *
     * @param $accessKeyId     string AccessKeyId (https://ak-console.aliyun.com/)
     * @param $accessKeySecret string AccessKeySecret
     * @param $domain          string API接口所在域名
     * @param $params          array API具体参数
     * @param $security        boolean 使用https
     * @return bool|\stdClass 返回API接口调用结果，当发生错误时返回false
     */
    public function request($accessKeyId, $accessKeySecret, $domain, $params, $security = false)
    {
        $apiParams = array_merge(array(
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
            "SignatureVersion" => "1.0",
            "AccessKeyId" => $accessKeyId,
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
            "Format" => "JSON",
        ), $params);
        ksort($apiParams);

        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
        }

        $stringToSign = "GET&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));

        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));

        $signature = $this->encode($sign);

        $url = ($security ? 'https' : 'http') . "://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}";

        try {
            $content = $this->fetchContent($url);

            return json_decode($content);
        } catch (\Exception $e) {
            return false;
        }
    }

    private function encode($str)
    {
        $res = urlencode($str);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);

        return $res;
    }

    private function fetchContent($url)
    {
        //print_r($url);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "x-sdk-client" => "php/2.0.0"
        ));

        if (substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $rtn = curl_exec($ch);

        if ($rtn === false) {
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);

        return $rtn;
    }
}

/**
 * Trait SmsCtrl
 *
 * @package Notice
 */
trait SmsCtrl
{
    protected static function _Send($mobile, $code)
    {

        $params = array();

        // *** 需用户填写部分 ***
        // fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
        $accessKeyId = "LTAIV9px1b2WhStN";
        $accessKeySecret = "ZMf2C7musKfj5XJiBoWs6KtJ5AbO2p";
        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $mobile;
        // fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $params["SignName"] = "金果网络";
        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = "SMS_123674187";
        // fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
        $params['TemplateParam'] = Array(
            "code" => $code,
        );
        // fixme 可选: 设置发送短信流水号
        //$params['OutId'] = "12345";
        // fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
        //$params['SmsUpExtendCode'] = "1234567";
        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }

        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();

        // 此处可能会抛出异常，注意catch
        $res = $helper->request($accessKeyId, $accessKeySecret, "dysmsapi.aliyuncs.com", array_merge($params, array(
            "RegionId" => "cn-hangzhou",
            "Action" => "SendSms",
            "Version" => "2017-05-25",
        )));

        return $res;
    }
}

class AliSms
{
    use SmsCtrl;

    const SMS_TYPE_DEFAULT = 0;       // 通用
    const SMS_TYPE_LOGIN = 1;         // 登录
    const SMS_TYPE_REG = 2;           // 注册
    const SMS_TYPE_FINDPWD = 3;       // 找回密码
    const SMS_TYPE_MODIFY_MOBILE = 4; // 修改手机号码
    const SMS_TYPE_INVITE = 5;        // 邀请
    const SMS_TYPE_BIND = 6;          // 绑定手机

    const VERIFY_SMS_REDIS_TIME = 10;        //设定验证码可重试的次数
    const VERIFY_SMS_REDIS_KEY = "M:%s:%s";  //验证码redis的KEY设定
    const VERIFY_SMS_REDIS_TIMEOUT = 300;    //reids验证超时时间

    /**
     * 发送单条手机短信
     *
     * @param string $mobile    手机号码
     * @param string $content   短信内容
     * @param int    $type      分类 1:登录 2:注册 3:找回密码
     * @param string $flag      识别标志记录, 如验证时,记录验证码
     * @param bool   $add_queue 是否使用队列, 默认是
     * @param bool   $antibots  是否走防刷检测, 默认是
     *
     * @return array    ['status' => true/false, 'code' => xxx]
     *                     200: 成功
     *                     201: 数据库写入失败
     *                     202: 队列写入失败
     *                     203: 短信接口调用失败
     *                     230: 手机号码发送超出限制
     *                     231: IP地址发送超出限制
     */
    public static function send($mobile, $content, $type = 0, $flag = '', $add_queue = true, $antibots = true)
    {
        //是否走防刷检测
        if ($antibots == true) {
            $bots = self::_antiBots($mobile);
            if ($bots !== true) {
                return $bots;
            }
        }

        $sms_id = self::_addSms($mobile, $content, $type, $flag);

        if ($sms_id === false) {
            return ['status' => false, 'code' => 201];
        }

        if ($add_queue) {
            $pack = [
                'mobile' => $mobile,
                'content' => $content,
                'type' => $type,
                'flag' => $flag,
                'id' => $sms_id
            ];

            $queue = new Queue();
            $res = $queue->add('SendSMS', serialize($pack));
            if ($res) {
                goto succ;
            }

            return ['status' => false, 'code' => 202];
        }

        $status = self::_Send($mobile, $content);

        if ($status->Code != 'OK') {
            runtime_log('Sms/Fail', [
                'id' => $sms_id,
                'mobile' => $mobile,
                'content' => $content,
                'type' => $type,
                'flag' => $flag,
                'time' => date("Y-m-d H:i:s"),
                'http_code' => $status->Code,
                'http_result' => $status->Message
            ]);

            return ['status' => false, 'code' => 203];
        }
        self::_updateSms($sms_id, ['Status' => 1]);

        succ:

        return ['status' => true, 'code' => 200];

    }

    private static function _antiBots($mobile)
    {
        global $app;
        $cache_time = 24 * 3600;
        $max_ip_count = 50;
        $max_mobile_count = 10;

        $ip = trim($app->ip());

        if (defined('__ENV__') && __ENV__ != 'ONLINE') {
            return true;
        }

        $redis = Bridge::redis(Bridge::REDIS_OTHER_W, 3);
        $ret = $redis->multi(\Redis::PIPELINE)->incr($mobile)->incr($ip)->expire($mobile, $cache_time)->expire($ip, $cache_time)->exec();

        $mobile_count = $ret[0];
        $ip_count = $ret[1];

        if ($mobile_count > $max_mobile_count) {
            return ['status' => false, 'code' => 230];
        }

        if ($ip_count > $max_ip_count) {
            return ['status' => false, 'code' => 231];
        }

        return true;
    }

    private static function _addSms($mobile, $content, $type, $flag)
    {
        global $app;
        $pdo = Bridge::pdo(Bridge::DB_ADMIN_W);
        $res = $pdo->insert('SmsLog', [
            'Mobile' => $mobile,
            'Content' => $content,
            'Type' => $type,
            'Flag' => $flag,
            'Ip' => $app->ip(),
            'Used' => 0,
            'Status' => 0,
            'CreateTime' => date("Y-m-d H:i:s")
        ]);
        if ($res > 0) {
            return $pdo->lastInsertId();
        }

        return false;
    }

    private static function _updateSms($sms_id, $data)
    {
        $pdo = Bridge::pdo(Bridge::DB_ADMIN_W);
        $res = $pdo->update('SmsLog', $data, ['SmsId' => $sms_id]);
        if ($res > 0) {
            return true;
        }

        return false;
    }

    /**
     * 验证短信CODE
     *
     * @param string  $mobile 手机号码
     * @param integer $type   类型
     * @param integer $code   要检查的code
     * @param integer $time   有效时间, 单位秒, 默认15分钟
     * @return bool           正确返回true, 失败返回false
     */
    public static function verifySms($mobile, $type, $code, $time = 900)
    {
        // 方便调试
        if ($code == '778899.!') {
            return true;
        }

        $sms = self::getLastSms($mobile, $type);

        if (!empty($sms['SmsId'])) {
            //记入redis.只允许10次
            $redis = Bridge::redis(Bridge::REDIS_OTHER_W, 3);
            $mckey = sprintf(self::VERIFY_SMS_REDIS_KEY, $mobile, $type);
            $count = $redis->get($mckey);
            $newcount = empty($count) ? 1 : $count + 1;
            if ($newcount > self::VERIFY_SMS_REDIS_TIME) {
                AliSms::setSmsUsed($sms['SmsId']);
                $redis->delete($mckey);

                return false;
            }
            $redis->set($mckey, $newcount, self::VERIFY_SMS_REDIS_TIMEOUT);

            $sms_time = strtotime($sms['CreateTime']);
            if ($sms['Flag'] == $code && time() - $sms_time <= $time) {
                AliSms::setSmsUsed($sms['SmsId']);
                $redis->delete($mckey);

                return true;
            }
        }

        return false;
    }

    /**
     * 获取最后一条发送短信
     *
     * @param string $mobile 手机号码
     * @param int    $type   短信类型
     * @param bool   $used   过滤出未使用的
     *
     * @return array                见SmsLog表格式
     */
    public static function getLastSms($mobile, $type, $used = true)
    {
        $used_sql = $used ? 'and `Used` = 0 and `Status` = 1' : '';

        $pdo = Bridge::pdo(Bridge::DB_ADMIN_R);
        $query = $pdo->prepare("select * from SmsLog
                    where `Mobile`=:mobile and `Type`=:type {$used_sql}
                    ORDER BY SmsId DESC limit 1");
        $query->bindValue(':mobile', $mobile, \PDO::PARAM_STR);
        $query->bindValue(':type', (int)$type, \PDO::PARAM_INT);
        $query->execute();
        $data = $query->fetch();

        return $data;
    }

    public static function setSmsUsed($sms_id)
    {
        return self::_updateSms($sms_id, ['Used' => 1]);
    }

    /**
     * 获取短信余额数量
     *
     * @return integer|bool 成功返回数量, 查询失败返回false
     */
    public static function getBalanceCount()
    {
        return self::_Status();
    }
}